package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.SkuImagesEntity;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;
import com.atguigu.gulimall.product.entity.SpuInfoDescEntity;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.webvo.SkuItemVo;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Consumer;
import java.util.function.Supplier;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuIfo(SkuInfoEntity skuInfoEntity) {
        this.save(skuInfoEntity);
    }

    /*
        key:
        catelogId: 0
        brandId: 0
        min: 0
        max: 0
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        /**
         * key:
         * catelogId: 0
         * brandId: 0
         * min: 0
         * max: 0
         */
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
                wrapper.eq("sku_id",key).or().like("sku_name",key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){

            queryWrapper.eq("catalog_id",catelogId);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("brand_id",brandId);
        }

        String min = (String) params.get("min");
        if(!StringUtils.isEmpty(min)){
            queryWrapper.ge("price",min);
        }

        String max = (String) params.get("max");

        if(!StringUtils.isEmpty(max)  ){
            try{
                BigDecimal bigDecimal = new BigDecimal(max);

                if(bigDecimal.compareTo(new BigDecimal("0"))==1){
                    queryWrapper.le("price",max);
                }
            }catch (Exception e){

            }

        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> querySkuBySpuId(Long spuId) {
        List<SkuInfoEntity> infoEntities =
                this.baseMapper.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return infoEntities;
    }


    //返回详情页信息
    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        /**
         * 1.为什么一定要使用自定义的线程池？
         * 2.执行策略：
         *  1->3,4,5
         *  2
         * 3.allof()作用
         */
        //1.sku基本信息：title,price
        CompletableFuture<SkuInfoEntity> infoFture = CompletableFuture.supplyAsync(new Supplier<SkuInfoEntity>() {
            @Override
            public SkuInfoEntity get() {
                SkuInfoEntity info = getById(skuId);
                skuItemVo.setInfo(info);
                return info;
            }
        }, executor);

        //3.销售版本组合：颜色、版本、内存
        CompletableFuture<Void> saleThread = infoFture.thenAcceptAsync(new Consumer<SkuInfoEntity>() {
            @Override
            public void accept(SkuInfoEntity skuInfoEntity) {
                List<SkuItemVo.ItemSaleAttrsVo> saleAttr = skuSaleAttrValueService.getSkuSaleAttrValue(skuInfoEntity.getSpuId());
                skuItemVo.setSaleAttr(saleAttr);
            }
        }, executor);

        //4.spu的商品介绍（sku共享）：销售属性+展示图
        CompletableFuture<Void> descThread = infoFture.thenAcceptAsync(new Consumer<SkuInfoEntity>() {
            @Override
            public void accept(SkuInfoEntity skuInfoEntity) {
                SpuInfoDescEntity desc = spuInfoDescService.getById(skuInfoEntity.getSpuId());
                skuItemVo.setDesc(desc);
            }
        }, executor);

        //5.规格与包装：所有属性分组下的所有属性
        CompletableFuture<Void> attrThread = infoFture.thenAcceptAsync(new Consumer<SkuInfoEntity>() {
            @Override
            public void accept(SkuInfoEntity skuInfoEntity) {
                Long catalogId = skuInfoEntity.getCatalogId();
                List<SkuItemVo.SkuItemSaleAttrVo> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(skuInfoEntity.getSpuId(), catalogId);
                skuItemVo.setGroupAttrs(groupAttrs);
            }
        }, executor);

        //2.sku轮播图片
        CompletableFuture<Void> imagesThread = CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                List<SkuImagesEntity> skuImagesEntities = skuImagesService.getImagesBySkuId(skuId);
                skuItemVo.setImages(skuImagesEntities);
            }
        }, executor);

        //等待所有任务执行结束
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(infoFture,saleThread, descThread, attrThread, imagesThread);
        voidCompletableFuture.get();

        return skuItemVo;
    }

}